﻿using System.Collections.Generic;
using ApplicationGenerator.BusinessModule.Elements;
using ApplicationGenerator.BusinessModule.MetaElements;
using ApplicationGenerator.BusinessModule.Interfaces;

namespace ApplicationGenerator.Forms.Utilities
{
    public class PathValidator
    {
        public static bool ValidatePath(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return false;
            }

            string[] arrayPathParts = path.Split(new char[] { '.' });
            if (arrayPathParts.Length < 2 || arrayPathParts.Length % 2 != 0)
            {
                return false;
            }

            IMetaModelCollection metaAdapterCollection = (new FacadeFactory()).CreateMetaModelFacade().MetaModelCollection;
            IList<string> pathPartsList = new List<string>();
            foreach (string pathPart in arrayPathParts)
            {
                pathPartsList.Add(pathPart);
            }

            return ValidateParentAndChild(metaAdapterCollection, pathPartsList);
        }

        public static bool ValidateParentAndChild(IMetaModelCollection adapterCollection, IList<string> pathPartsList)
        {
            if (pathPartsList.Count == 0)
            {
                return true;
            }

            IMetaModel metaAdapter = adapterCollection[pathPartsList[0]];
            if (metaAdapter == null)
            {
                return false;
            }

            if (metaAdapter.MetaFieldCollection[pathPartsList[1]] == null)
            {
                return false;
            }


            pathPartsList.RemoveAt(0);
            pathPartsList.RemoveAt(0);

            return ValidateParentAndChild(adapterCollection, pathPartsList);
        }
    }
}
